import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/count_down_timer.dart';
import 'package:cbec_app/entity/home/content/superior_special_price_entity.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';

import '../../../pages/goods/binding/goods_detail_binding.dart';
import '../../../pages/goods/view/goods_detail_page.dart';
import '../../base/base_image.dart';
import '../../base/base_interactive.dart';
import 'decoration_special_super_product_ctr.dart';

class DecorationSpecialSuperProduct extends StatefulWidget {
  final SuperiorSpecialPriceEntity model;
  const DecorationSpecialSuperProduct({
    super.key,
    required this.model,
  });

  @override
  State<DecorationSpecialSuperProduct> createState() => _DecorationSpecialSuperProductState();
}

class _DecorationSpecialSuperProductState extends State<DecorationSpecialSuperProduct> {
  late DecorationSpecialSuperProductCtr controller;

  @override
  void initState() {
    super.initState();
    String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    controller = Get.put(DecorationSpecialSuperProductCtr(), tag: timestamp);
  }

  @override
  Widget build(BuildContext context) {
    controller.fetchData(widget.model);
    return Obx(() {
      if (controller.result.isEmpty) {
        return const SizedBox(); // 数据为空时的状态
      }
      return Container(
        color: Tools.fromHex('#f4f4f4'),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(widget.model.bdr!.toDouble() ?? 0)),
          child: Container(
            margin: EdgeInsets.only(
              left: widget.model.pageMarginLeft!.toDouble(), // page_margin_left
              top: widget.model.pageMarginTop!.toDouble(),
              right: widget.model.pageMarginRight!.toDouble(),
              bottom: widget.model.pageMarginBottom!.toDouble(),
            ),
            decoration: BoxDecoration(
              color: widget.model.bgColor != null ? Tools.fromHex(widget.model.bgColor!) : Colors.transparent,
              borderRadius: BorderRadius.all(
                Radius.circular(widget.model.bdr?.toDouble() ?? 0),
              ),
              image: widget.model.bgImage != null && widget.model.bgImage!.attachmentUrl!.isNotEmpty
                  ? DecorationImage(
                      image: NetworkImage(widget.model.bgImage!.attachmentUrl!),
                      fit: BoxFit.cover,
                      alignment: Alignment.topCenter, // 图片从顶部对齐
                    )
                  : null,
            ),
            child: Column(
              children: [
                TopView(result: controller.result, model: widget.model),
                Center(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      children: [
                        BottomView(result: controller.result, model: widget.model),
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      );
    });
  }
}

class TopView extends StatelessWidget {
  final SuperiorSpecialPriceEntity model;
  final Map<String, dynamic> result;
  const TopView({super.key, required this.result, required this.model});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(
        left: model.countdownMarginLeft!.toDouble(),
        top: model.countdownMarginTop!.toDouble(),
        bottom: model.countdownMarginBottom!.toDouble(),
      ),
      child: result.isEmpty
          ? const SizedBox()
          : Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween, // 内容左右对齐
              children: [
                CountDownWidget(result: result, model: model), // 靠左显示的倒计时
                Visibility(
                  visible: model.moreShow == '1',
                  child: Padding(
                    padding: const EdgeInsets.only(right: 10, top: 5),
                    child: lookMore(model, () {
                      Get.toNamed(Routes.discountGoodsList);
                    }),
                  ),
                ), //靠右显示的按钮
              ],
            ),
    );
  }
}

class BottomView extends StatelessWidget {
  final Map<String, dynamic> result;
  final SuperiorSpecialPriceEntity model;
  const BottomView({
    super.key,
    required this.result,
    required this.model,
  });

  @override
  Widget build(BuildContext context) {
    final Map<String, dynamic> goodsList = result['goodsList'];
    final List<dynamic> rawProducts = goodsList['list'];
    final List<Map<String, dynamic>> products = rawProducts.map((product) => product as Map<String, dynamic>).toList();

    return Container(
      // padding: EdgeInsets.only(
      //   left: model.goodsMarginLeft2!.toDouble(), //goods_margin_left_2
      //   top: model.pageMarginTop2!.toDouble(), // page_margin_top_2
      //   bottom: model.pageMarginBottom2!.toDouble(), // page_margin_bottom_2
      // ),
      child: products.isNotEmpty
          ? ProductListWidget(
              products: products,
              model: model,
            )
          : const SizedBox(),
    );
  }
}

//----------------------上面部分------------------------------//
class CountDownWidget extends StatelessWidget {
  final SuperiorSpecialPriceEntity model;
  final Map<String, dynamic> result;
  const CountDownWidget({super.key, required this.result, required this.model});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(top: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(
              left: 10,
            ),
            child: Text('距结束: ', style: setTextStyle(14, FontWeight.normal, Tools.fromHex(model.activityNameColor!))),
          ),
          CountDownTimer(
            timeStamp: result['endTime'] == null ? 0 : int.parse(result['endTime']) * 1000,
            timeStyle: TimeStyle.hhmmss,
            countDownStyle: CountDownStyle.box,
            boxBackgroundColor: Tools.fromHex(model.countdownBgColor!),
            colonColor: Tools.fromHex(model.activityNameColor!),
            style: setTextStyle(12, FontWeight.normal, Tools.fromHex(model.countdownTextColor!)),
          )
        ],
      ),
    );
  }
}

///查看更多样式
Widget lookMore(SuperiorSpecialPriceEntity model, VoidCallback onPressed) {
  switch (model.moreBtnStyle) {
    case 2: //文字+箭头
      return BaseInteractive(
        childWidget: Row(
          children: [
            Text(model.moreBtnText!, style: setTextStyle(14, FontWeight.normal, Tools.fromHex(model.moreBtnColor!))),
            Icon(
              Icons.navigate_next,
              color: Tools.fromHex(model.moreBtnColor!),
            )
          ],
        ),
        onClick: () {
          onPressed();
        },
      );
    case 3: //箭头
      return BaseInteractive(
        childWidget: Icon(
          Icons.navigate_next,
          color: Tools.fromHex(model.moreBtnColor!),
        ),
        onClick: () {
          onPressed();
        },
      );
    case 4: //圆角文字按钮
      return BaseInteractive(
        childWidget: Container(
          padding: const EdgeInsets.all(5),
          decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(20)), border: Border.all(color: Tools.fromHex(model.moreBtnColor!))),
          child: Text(model.moreBtnText!, style: setTextStyle(14, FontWeight.normal, Tools.fromHex(model.moreBtnColor!))),
        ),
        onClick: () {
          onPressed();
        },
      );
    case 1: //文字
    default:
      return BaseInteractive(
        onClick: () {
          onPressed();
        },
        childWidget: Text(model.moreBtnText!, style: setTextStyle(14, FontWeight.w400, Tools.fromHex(model.moreBtnColor!))),
      );
  }
}

//----------------------下面部分------------------------------//

class ProductListWidget extends StatelessWidget {
  final SuperiorSpecialPriceEntity model;
  final List<Map<String, dynamic>> products;

  const ProductListWidget({super.key, required this.products, required this.model});

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      padding: EdgeInsets.zero,
      scrollDirection: Axis.horizontal,
      child: Row(
        children: products.map((item) {
          // print("Rendering item: $item"); // 在这里打印 item
          return ProductItemWidget(item: item, model: model);
        }).toList(), // 修复 .toList() 的位置
      ),
    );
  }
}

class ProductItemWidget extends StatelessWidget {
  final SuperiorSpecialPriceEntity model;
  final Map<String, dynamic> item;
  const ProductItemWidget({
    super.key,
    required this.item,
    required this.model,
  });

  BoxDecoration getBoxDecoration() {
    String sizeType = model.sizeType!;
    // border_radius_type 1直角 2圆角
    String borderRadiusType = model.borderRadiusType!;
    BorderRadius borderRadius = borderRadiusType == '1' ? BorderRadius.zero : const BorderRadius.all(Radius.circular(5));

    switch (sizeType) {
      case '0':
        return DecorationProvider.getDecoration(ContainerStyleType.borderWhite, borderRadius);
      case '1':
        return DecorationProvider.getDecoration(ContainerStyleType.cardShadow, borderRadius);
      case '2':
        return DecorationProvider.getDecoration(ContainerStyleType.borderWhite, borderRadius);
      case '3':
        return DecorationProvider.getDecoration(ContainerStyleType.noBorderTransparent, borderRadius);
      default:
        return DecorationProvider.getDecoration(ContainerStyleType.borderWhite, borderRadius);
    }
  }

  bool isShowTitle() {
    return model.showTitle == '1';
  }

  bool isShowPrice() {
    return model.price == '1';
  }

  double imageW() {
    return ((ScreenUtil().screenWidth - 40) * model.per!) / 100.0;
  }

  CrossAxisAlignment getTextAlignType() {
    String textAlignType = model.textAlignType!;
    return textAlignType == 'left' ? CrossAxisAlignment.start : CrossAxisAlignment.center;
  }

  // 商品外间距
  double goodsMargin() {
    return model.goodsMargin!.toDouble();
  }

  // 商品角标
  bool isShowCornerMark() {
    return model.showCornerMark!;
  }

  ///获取角标url
  String getBadgeUrl() {
    switch (model.cornerMarkType) {
      case '1': //热卖
        return 'hot_ch.png';
      case '2': //NEW
        return 'new.png';
      case '3': //HOT
        return 'hot.png';
      case '4': //自定义
        return model.cornerMarkImage!;
      case '0': //新品
      default:
        return 'new_ch.png';
    }
  }

  ///获取角标
  Widget getBadge() {
    return Positioned(
        top: 0,
        left: 0,
        child: Container(
          alignment: Alignment.center,
          child: BaseImage(
            url: getBadgeUrl(),
            width: 32,
            height: 32,
          ),
        ));
  }

  ///商品图片圆角
  double getRadius() {
    return model.borderRadiusType == '1' ? 0.0 : 3.0;
  }

  double imageH() {
    String displayScale = model.displayScale!;
    switch (displayScale) {
      case '0': // 3:2
        return imageW() * (2 / 3.0);
      case '1': // 1:1
        return imageW();
      case '2': // 3:4
        return imageW() * (4 / 3.0);
      case '3': // 16:9
        return imageW() * (9 / 16.0);
      default:
        return imageW() * (2 / 3.0);
    }
  }

  EdgeInsets getImageFillStyle() {
    String imageFillStyle = model.imageFillStyle!;
    return imageFillStyle == '1' ? EdgeInsets.zero : const EdgeInsets.symmetric(horizontal: 5, vertical: 20);
  }

  FontWeight titleTextStyle() {
    return model.textStyleType == '1' ? FontWeight.normal : FontWeight.bold;
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        final id = item['goodsId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      child: Container(
        margin: EdgeInsets.all(goodsMargin()),
        decoration: getBoxDecoration(),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: getImageFillStyle(),
              child: Stack(
                children: [
                  Image.network(
                    item['mainImage'],
                    height: imageH(),
                    width: imageW(),
                    fit: BoxFit.cover,
                  ),
                  getBadge(),
                ],
              ),
            ),
            SizedBox(
              width: imageW(),
              child: Column(
                crossAxisAlignment: getTextAlignType(),
                children: [
                  Visibility(
                    visible: isShowTitle(),
                    child: Text(
                      item['commodityName'],
                      style: TextStyle(fontSize: 14, fontWeight: titleTextStyle()),
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Visibility(
                    visible: isShowPrice(),
                    child: RichText(
                      text: TextSpan(
                        children: [
                          TextSpan(
                            text: '¥',
                            style: TextStyle(
                              color: Tools.fromHex('#F83E2D'), // 设置 ¥ 的颜色
                              fontSize: 10, // 设置 ¥ 的字体大小
                              fontWeight: FontWeight.bold, // 设置 ¥ 的字体粗细
                            ),
                          ),
                          TextSpan(
                            text: item['seckillPrice'].toString(),
                            style: TextStyle(
                              color: Tools.fromHex('#F83E2D'), // 设置价格的颜色
                              fontSize: 14, // 设置价格的字体大小
                              fontWeight: FontWeight.bold, // 设置价格的字体粗细
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(height: 10),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
